<template>
  <div class="">
      <div>
          <div style="padding:20px;" >
               <Form ref="formItem"   :model="formItem" label-position="top"  >
                   <div style="width:320px;">
                        <FormItem label="标题" prop="title">
                            <Input v-model="formItem.title"></Input>
                        </FormItem>
                        <!-- <FormItem label="副标题" prop="otherTitle">
                            <Input v-model="formItem.otherTitle"></Input>
                        </FormItem> -->
                        <FormItem label="作者" prop="author">
                            <Input v-model="formItem.author"></Input>
                        </FormItem>
                        <FormItem label="发布日期" prop="date">
                            <Row>
                                <Col span="12">
                                    <DatePicker type="date" :options="dateFrom" v-model="formItem.date" placeholder="选择日期" style="width: 200px"></DatePicker>
                                </Col>
                            </Row>
                        </FormItem>
                        <FormItem label="简述" prop="otherTitle"><!--用于显示详情页之前的值-->
                                <Input v-model="formItem.otherTitle" type="textarea" :autosize="{minRows: 1,maxRows: 10}" placeholder="请输入..."></Input>
                                <!-- 使用autosize对文本域的初始宽度以及高度进行设置 -->
                        </FormItem>
                        <FormItem label="类型" prop="style">
                            <!-- 这里使用树便于管理 -->
                            <Tree empty-text @on-select-change="getStyleSelectedNodes" :data="styleData"  ></Tree>
                            <!-- :load-data="loadStyleData" -->
                        </FormItem>
                        <FormItem  label="标签" prop="tips">
                            <!-- 由于标签中不存在多级树的层级关系，使用checkbox的方式进行标签的渲染 -->
                            <!-- <Tree show-checkbox empty-text @on-check-change="getTipsCheckedNodes" :data="tipsData" :load-data="loadTipsData"></Tree> -->
                            <CheckboxGroup v-model="formItem.tips">
                                <Checkbox label="twitter">
                                    <Icon type="social-twitter"></Icon>
                                    <span>Twitter</span>
                                </Checkbox>
                                <Checkbox label="facebook">
                                    <Icon type="social-facebook"></Icon>
                                    <span>Facebook</span>
                                </Checkbox>
                                <Checkbox label="github">
                                    <Icon type="social-github"></Icon>
                                    <span>Github</span>
                                </Checkbox>
                                <Checkbox label="snapchat">
                                    <Icon type="social-snapchat"></Icon>
                                    <span>Snapchat</span>
                                </Checkbox>
                            </CheckboxGroup>
                        </FormItem>
                    </div>
                    <!--待处理-->
                    <!-- quill-editor插件标签 分别绑定各个事件-->
                    <FormItem label="编辑器" prop="textarea">
                        <!-- 默认是以base64的方式进行图片的储存 -->
                        <quill-editor v-model="formItem.textarea" 
                            :options="editorOption"
                            ref="myQuillEditor"  
                            @blur="onEditorBlur($event)"  
                            @focus="onEditorFocus($event)"  
                            @ready="onEditorReady($event)"  
                            @change="onEditorChange($event)">  
                        </quill-editor>  
                        <Upload
                            multiple
                            style="display:none"
                            ref="up"
                            :show-upload-list="true"
                            :on-success="handleSuccess"
                            :format="['jpg','jpeg','png']"
                            :max-size="4096"
                            :on-format-error="handleFormatError"
                            :on-exceeded-size="handleMaxSize"
                            :before-upload="handleBeforeUpload"
                            type="drag"
                            name="avatar"
                            action="http://localhost:3000/upload/imgfile">
                            <input id="upload" />
                        </Upload>
                        <div>
                            {{ formItem.textarea }}
                        </div>
                    </FormItem>
                    <FormItem>
                        <Button type="primary" @click="handleSubmit('formItem')">提交</Button>
                        <Button type="ghost" @click="handleReset('formItem')" style="margin-left: 8px">重置</Button>
                    </FormItem>
                </Form>
          </div>
      </div>
  </div>
</template>

<script>
    import {quillRedefine} from 'vue-quill-editor-upload'//将图片模块引入
    export default {
        components: {quillRedefine},//引入相关的quillRedefine的组件
        data () {
            return {
                visible: false,  
                uploadList: [],  
                editorOption:{},
                formItem: {
                    title: '',
                    otherTitle: '',
                    author: '',
                    date: '',
                    textarea:'<h3>请输入吧</h3>',//富文本编辑器内容
                    imgUrl:'',
                    style:[],//类型
                    tips:[]//标签
                },
                styleData:[{
                    title: '...',
                    loading: false,
                    children: []
                }],
                tipsData:[],
                // ruleFromItem: {//表单验证
                //     title: [
                //         { required: true, message: '姓名不能为空', trigger: 'blur' }
                //     ],
                //     otherTitle: [
                //         { required: true, message: '请填写密码', trigger: 'blur' },
                //         { type: 'string', min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
                //     ],
                //     city: [
                //         { required: true, message: '请选择城市', trigger: 'change' }
                //     ],
                //     date: [
                //         { required: true, type: 'date', message: '您的生日', trigger: 'change' }
                //     ]
                // },
                dateFrom: {//时间
                    shortcuts: [
                        {
                            text: '今天',
                            value () {
                                return new Date();
                            },
                            onClick: (picker) => {
                                this.$Message.info('点击了今天');
                            }
                        },
                        {
                            text: '昨天',
                            value () {
                                const date = new Date();
                                date.setTime(date.getTime() - 3600 * 1000 * 24);
                                return date;
                            },
                            onClick: (picker) => {
                                this.$Message.info('点击了昨天');
                            }
                        },
                        {
                            text: '一周前',
                            value () {
                                const date = new Date();
                                date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                                return date;
                            },
                            onClick: (picker) => {
                                this.$Message.info('点击了一周前');
                            }
                        }
                    ]
                }
            }
        },
        created () {
            // this.editorOption = quillRedefine(
            //     {
            //         uplpadConfig: { // 图片上传的设置
            //             action: '',  // 必填参数 图片上传地址
            //             res: (respnse) => {
            //                 console.log(respnse)
            //             return respnse.info  // 这里切记要return回你的图片地址
            //             },
            //         }
            //     }
            // )
        },
        computed: {  
            editor() {  
                return this.$refs.myQuillEditor.quill  
            },  
        },  
        methods: {
            getStyleSelectedNodes() {//"类型"节点的单击返回值
                this.formItem.style.push(arguments[0])   
            },
            getTipsCheckedNodes() {
                this.formItem.tips.push(arguments[0])   
            },
            loadStyleData (item, callback) {//加载类型的树数据
                setTimeout(() => {
                    this.$http({
                        method:"GET",
                        url:'http://localhost:3000/cate2/list',
                    })
                    .then((response) => {
                        this.styleData = response.data;
                        callback(this.styleData);    
                    })
                    .catch((response) => {
                        console.log(response)
                    });
                },400)
            },
            loadTipsData (item, callback) {//加载tips的树数据
                setTimeout(() => {
                    this.$http({
                        method:"GET",
                        url:'http://localhost:3000/cate2/list',
                    })
                    .then((response) => {
                        this.tipsData = response.data;
                        // callback(this.tipsData);    
                    })
                    .catch((response) => {
                        console.log(response)
                    });
                },400)
                // setTimeout(() => {
                //     this.$http({
                //         method:"GET",
                //         url:'http://localhost:3000/cate2/list',
                //     })
                //     .then((response) => {
                //         this.tipsData = response.data
                //         callback(this.tipsData);    
                //     })
                //     .catch((response) => {
                //         console.log(response)
                //     });
                // }, 400);
            },
            handleSubmit (name) {//添加数据
                this.$refs[name].validate((valid) => {
                    if (valid) {
                           this.$http({
                                method:"POST",
                                url:'http://localhost:3000/content/data',
                                data:this.formItem
                            })
                            .then((response) => {
                                console.log(response)
                                this.$Message.success('提交成功!');
                            })
                            .catch((response) => {
                                console.log(response)
                            });
                    } else {
                        this.$Message.error('表单验证失败!');
                    }
                })
            },
            handleReset (name) {
                this.$refs[name].resetFields();
            },
            // -----------------------------------------------------------------------------------------------------------------------------------------
            //以下都是编辑器的方法
            imgClick() {  
                $('#upload').click()  
            },  
            //成功回调  
            handleSuccess(response, file, fileList) {  
                if(response.code == 500) {  
                    this.$Message.error('上传失败!')  
                } else {  
                    this.$Message.success('上传成功!')  
                }  
                console.log(response.filename)  
                //重要========================
                //图片上传成功后，将路径写入去
                var range = this.$refs.myQuillEditor.quill;
                var length = range.index;
                this.$refs.myQuillEditor.quill.insertEmbed(length, 'image',response.filename);
                // ========================
            },  
            //报错的时候的警告
            handleFormatError (file) {
                this.$Notice.warning({
                    title: '文件格式不正确',
                    desc: '文件 ' + file.name + ' 格式不正确，请上传 jpg 或 png 格式的图片。'
                });
            },
            handleBeforeUpload () {
                const check = this.uploadList.length < 5;
                if (!check) {
                    this.$Notice.warning({
                        title: '最多只能上传 5 张图片。'
                    });
                }
                return check;
            },
            handleMaxSize (file) {
                this.$Notice.warning({
                    title: '超出文件大小限制',
                    desc: '文件 ' + file.name + ' 太大，不能超过 2M。'
                });
            },
            //Quill-edit配置默认的方法  
            onEditorBlur(editor) {  
                // console.log('editor blur!',editor)  
            },  
            onEditorFocus(editor) {  
                // console.log('editor focus!', editor)  
            },  
            onEditorReady(editor) {  
                // console.log('editor ready!', editor)  
            },  
            onEditorChange({editor,html,text}) {  
                // console.log('editor change!', editor, html, text)
                // this.formItem.textarea = html
            }  
        },
        created() {
            this.loadStyleData()
        },
         mounted() {

            //给img video按键绑定事件  
            this.$refs.myQuillEditor.quill.getModule('toolbar').addHandler('image', this.imgClick)  
            // this.$refs.myQuillEditor.quill.getModule('toolbar').addHandler('video', this.imgClick)  
        }
    }
</script>

<style lang='scss' scoped>

</style>
